# get_up_seq.R
# Joe Song
#
# Created: 10/10/2012

symbol.to.refseq <- function(gene.list)
{
  # gene.list must be a vector of either gene symbols or Refseq IDs, or a mixture, 
  # but not other identifiers.
  
  require(org.Hs.eg.db)
  # load IDs, symbol and gene descriptions
  refseq.id.table <- toTable(org.Hs.egREFSEQ)
  symbol.table <- toTable(org.Hs.egSYMBOL)

  gene.list <- toupper(gene.list)
  
  gene.list.refseq <- vector("character", length=length(gene.list))

  is.refseq <- gene.list %in% refseq.id.table[, "accession"]
  
  is.symbol <- gene.list %in% symbol.table[, "symbol"]
  
  which.symbol <- match( gene.list, symbol.table[, "symbol"] )
  
  symbol.gene_ids <- match(symbol.table[which.symbol, "gene_id"], refseq.id.table[, "gene_id"])
  
  gene.list.refseq[is.symbol] <- refseq.id.table[symbol.gene_ids[is.symbol], "accession"]
  gene.list.refseq[! is.symbol] <- gene.list[! is.symbol]

  invalid <- ! (is.refseq | is.symbol)

  if(! all(! invalid)) {

    cat("The following invalid genes have been removed:\n", gene.list[invalid], "\n")
    
    gene.list.refseq <- gene.list.refseq[ ! invalid ]

  }
  
  return(gene.list.refseq)
}

get.up.seq <- function(gene.list, number.bases.upstream=1000)
{
  gene.list.refseq <- symbol.to.refseq(gene.list)
  if(length(gene.list.refseq) > 0) {
    extract.five.utr.sequence (gene.list.refseq, number.bases.upstream)
  } else {
    cat("The gene list is empty.")
  }
}
